<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="filter-container">
          <div class="demo-input-suffix acea-row">
            <span class="seachTiele">状态：</span>
            <el-select v-model="tableFrom.couponIsOpen" placeholder="请选择" class="filter-item selWidth mr20"
                       @change="seachList" clearable>
              <el-option label="未开启" :value="0"/>
              <el-option label="开启" :value="1"/>
            </el-select>
            <span class="seachTiele">优惠券名称：</span>
            <el-input v-model="tableFrom.couponName" placeholder="请输入优惠券名称" class="selWidth" clearable>
              <el-button slot="append" icon="el-icon-search" size="small" @click="seachList"/>
            </el-input>
          </div>
        </div>
        <el-button size="small" @click="handleCreate"
                   style="margin-left: 5px">
          <i class="el-icon-apple"></i>
          添加优惠券
        </el-button>
        <!--        批量删除-->
        <el-button size="small" type="danger" @click="handleDelMenuBatch" v-hasPermi="['admin:coupon:delete']"
                   style="margin-left: 5px">
          <i class="el-icon-delete"></i>
          批量删除
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        :header-cell-style=" {fontWeight:'bold'}"
        @selection-change="handleSelectionChange"
      >


        //最前面加一个复选框
        <el-table-column type="selection" width="55"></el-table-column>


        <el-table-column
          prop="couponId"
          label="ID"
          min-width="50"
        />
        <el-table-column
          prop="couponName"
          label="优惠券名称"
          min-width="180"
        />
        <el-table-column
          prop="couponType"
          label="优惠券类型"
          min-width="80"
        >
        </el-table-column>
        <el-table-column
          prop="couponValue"
          label="面值"
          min-width="100"
        />
        <el-table-column
          prop="couponGetWay"
          label="领取方式"
          min-width="100"
          :formatter="formatCouponGetWay"
        ></el-table-column>

        <el-table-column
          prop="couponGetDate"
          min-width="130"
          label="领取日期"
        >
        </el-table-column>
        <el-table-column
          prop="couponUseDate"
          min-width="100"
          label="使用时间"
        >
        </el-table-column>
        <el-table-column
          prop="couponPublishNum"
          min-width="100"
          label="发布数量"
        >
          <template slot-scope="{ row }">
            <span v-if=" !row.couponIsLimited ">不限量</span>
            <div v-else>
              <span class="fa">发布：{{ row.couponTotal }}</span>
              <span class="sheng">剩余：{{ row.couponLastTotal }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="couponIsOpen"
          label="是否开启"
          min-width="130"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.couponIsOpen"
              :active-value="1"
              :inactive-value="0"
              active-text="开启"
              inactive-text="关闭"
              @click.native="onchangeIsShow(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" class="mr10" size="small" @click="receive(scope.row)"
                       v-hasPermi="['admin:coupon:user:list']">领取记录
            </el-button>
<!--            <el-button v-if="scope.row.couponIsOpen" type="text" size="small" class="mr10"-->
<!--                       @click="copy(scope.row.id)"-->
<!--                       v-hasPermi="['admin:coupon:info']">复制-->
<!--            </el-button>-->
            <el-button type="text" class="mr10" size="small" @click="handleUpdate(scope.row)"
                       >编辑
            </el-button>
            <el-button type="text" class="mr10" size="small" @click="handleDelMenu(scope.row)"
                       v-hasPermi="['admin:coupon:delete']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.pageSize"
          :current-page="tableFrom.pageNum"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <!--领取记录-->
    <el-dialog
      title="领取记录"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <el-table
        v-loading="Loading"
        :data="issueData.data"
        style="width: 100%"
      >
        <el-table-column
          prop="nickname"
          label="用户名"
          min-width="120"
        />
        <el-table-column label="用户头像" min-width="80">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 36px; height: 36px"
                :src="scope.row.avatar"
                :preview-src-list="[scope.row.avatar]"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="领取时间"
          min-width="180"
        />
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[10, 20, 30, 40]"
          :page-size="tableFromIssue.pageSize"
          :current-page="tableFromIssue.pageNum"
          layout="total, sizes, prev, pager, next, jumper"
          :total="issueData.total"
          @size-change="handleSizeChangeIssue"
          @current-change="pageChangeIssue"
        />
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-row :gutter="20">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="111px">
          <el-col :span="13">
            <el-form-item label="优惠券名称" prop="couponName" >
              <el-input v-model="form.couponName" placeholder="请输入优惠券名称" clearable >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="优惠券类型" prop="couponType" >
              <el-input v-model="form.couponType" placeholder="请输入优惠券类型" clearable >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="优惠券面值" prop="couponValue">
              <el-input-number v-model="form.couponValue" controls-position="right" :min="1" :max="1000"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="领取日期" prop="couponGetDate">
              <el-date-picker
                v-model="form.couponGetDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="使用有效期" prop="couponUseDate">
              <el-input-number v-model="form.couponUseDate" placeholder="天数"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="领取方式" prop="couponGetWay">
              <el-select v-model="form.couponGetWay" placeholder="请选择"
                         clearable>
                <el-option label="手动领取" :value="0"/>
                <el-option label="自动发放" :value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="是否限量" prop="couponPublishNum">
              <el-radio-group v-model="form.couponPublishNum" size="medium">
                <el-radio v-for="(item, index) in couponPublishNumOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="状态" prop="couponIsOpen">
              <el-radio-group v-model="form.couponIsOpen" size="medium">
                <el-radio v-for="(item, index) in couponIsOpenOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item size="large">
              <el-button type="primary" @click="submitForm">提交</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  marketingListApi,
  couponIssueStatusApi,
  // couponUserListApi,
  couponDeleteByIdApi,
  couponDeleteBatchApi,
  couponCreateApi,
  couponCopyApi
} from '@/api/marketing/coupon'
import {roterPre} from '@/settings'
import {checkPermi} from "@/utils/permission"; // 权限判断函数
export default {
  name: 'CouponList',
  data() {
    return {
      title: '',
      Loading: false,
      dialogVisible: false,
      roterPre: roterPre,
      listLoading: true,
      tableData: {
        data: [],
        total: 0
      },
      tableFrom: {
        pageNum: 1,
        pageSize: 20,
        couponName: '',
        couponIsOpen: '',
      },
      tableFromIssue: {
        pageNum: 1,
        pageSize: 10,
        couponId: ''
      },
      issueData: {
        data: [],
        total: 0
      },
      //获取的优惠券id列表
      ids: [],
      // 我写的代码 从这开始
      radio: '1',


      formData: {
        couponName: undefined,
        couponType: '1',
        couponValue: undefined,
        useNeed: undefined,
        youxiaoqi: undefined,
        field110: undefined,
        field112: undefined,
        couponGetWay: undefined,
        couponPublishNum: undefined,
        couponIsOpen: undefined,
      },
      rules: [],
      // rules: {
      //   couponName: [{
      //     required: true,
      //     message: '请输入优惠券名称',
      //     trigger: 'blur'
      //   }],
      //   couponType: [{
      //     required: true,
      //     message: '优惠券类型不能为空',
      //     trigger: 'change'
      //   }],
      //   couponValue: [{
      //     required: true,
      //     message: '优惠券面值',
      //     trigger: 'blur'
      //   }],
      //   useNeed: [{
      //     required: true,
      //     message: '使用门槛不能为空',
      //     trigger: 'change'
      //   }],
      //   youxiaoqi: [{
      //     required: true,
      //     message: '使用有效期不能为空',
      //     trigger: 'change'
      //   }],
      //   field110: [{
      //     required: true,
      //     message: '天数',
      //     trigger: 'blur'
      //   }],
      //   field112: [{
      //     required: true,
      //     message: '领取是否限时不能为空',
      //     trigger: 'change'
      //   }],
      //   couponGetWay: [{
      //     required: true,
      //     message: '领取方式不能为空',
      //     trigger: 'change'
      //   }],
      //   couponPublishNum: [{
      //     required: true,
      //     message: '是否限量不能为空',
      //     trigger: 'change'
      //   }],
      //   couponIsOpen: [{
      //     required: true,
      //     message: '状态不能为空',
      //     trigger: 'change'
      //   }],
      // },
      couponTypeOptions: [{
        "label": "通用券",
        "value": "通用券"
      }, {
        "label": "商品券",
        "value": "商品券"
      }, {
        "label": "品类券",
        "value": "品类券"
      }],
      useNeedOptions: [{
        "label": "有门槛",
        "value": 1
      }, {
        "label": "无门槛",
        "value": 2
      }],
      youxiaoqiOptions: [{
        "label": "天数",
        "value": 1
      }, {
        "label": "时间段",
        "value": 2
      }],
      field112Options: [{
        "label": "限时",
        "value": 1
      }, {
        "label": "不限时",
        "value": 2
      }],
      couponGetWayOptions: [{
        "label": "手动领取",
        "value": 1
      }, {
        "label": "新人券",
        "value": 2
      }, {
        "label": "赠送券",
        "value": 3
      }],
      couponPublishNumOptions: [{
        "label": "限量",
        "value": 1
      }, {
        "label": "不限量",
        "value": 2
      }],
      couponIsOpenOptions: [{
        "label": "开启",
        "value": 1
      }, {
        "label": "关闭",
        "value": 0
      }],

      open: false,
      form: {},
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    checkPermi,
    seachList() {
      this.tableFrom.pageNum = 1
      this.getList()
    },
    handleClose() {
      this.dialogVisible = false
    },
    submitForm() {
      console.log(this.form)
      // this.$refs['form'].validate(valid => {
        // if (!valid) {
      couponIssueStatusApi(this.form).then(() => {
            console.log("this.form")
            this.$message.success("保存成功！正在关闭")
            this.open = false;
          })
          this.getList()
        // }
        // TODO 提交表单
      // })
    },
    handleCreate() {
      this.form = {}
      this.open = true
    },
    copy(id) {
      couponCopyApi(id).then((res) => {
        this.$message.success("复制成功，请稍后")
        this.getList();
      }).catch((error) => {
        this.$message("复制失败！")
      })
    },
    formatCouponGetWay(row) {
      if (row.couponGetWay === 0) {
        return "手动领取";
      } else if (row.couponGetWay === 1) {
        return "自动发放";
      } else {
        return "未知方式"; // 或者根据需要返回其他默认值
      }
    },
    // 领取记录
    receive(row) {
      this.dialogVisible = true
      this.tableFromIssue.couponId = row.id
      this.getIssueList()
    },
    // 列表
    getIssueList() {
      this.Loading = true
      couponUserListApi(this.tableFromIssue).then(res => {
        this.issueData.data = res.list
        this.issueData.total = res.total
        this.Loading = false
      }).catch(res => {
        this.Loading = false
        this.$message.error(res.message)
      })
    },
    pageChangeIssue(pageNum) {
      this.tableFromIssue.pageNum = pageNum
      this.getIssueList()
    },
    handleSizeChangeIssue(val) {
      this.tableFromIssue.pageSize = val
      this.getIssueList()
    },
    // 列表
    getList() {
      this.listLoading = true
      marketingListApi(this.tableFrom).then((res) => {
        console.log(res.rows)
        this.tableData.data = res.rows
        this.tableData.total = res.total
        this.listLoading = false
      }).catch(res => {
        this.listLoading = false
      })
    },
    pageChange(pageNum) {
      this.tableFrom.pageNum = pageNum
      this.getList()
    },
    handleSizeChange(val) {
      this.tableFrom.pageSize = val
      this.getList()
    },
    // 修改状态
    onchangeIsShow(row) {
      couponIssueStatusApi({couponId: row.couponId, couponIsOpen: row.couponIsOpen}).then(() => {
        this.$message.success('修改成功')
        this.getList()
      }).catch(() => {
        row.couponIsOpen = !row.couponIsOpen
      })
    },
    handleDelMenu(rowData) {
      this.$confirm('确定删除当前数据?').then(() => {
        couponDeleteByIdApi(rowData.couponId).then(data => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    handleUpdate(row){
      this.form = row
      this.open = true
    },

    //获取选中的id转化为list
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.couponId)
    },

    //批量删除
    handleDelMenuBatch() {
      this.$confirm('确定删除这些优惠券?').then(() => {
        couponDeleteBatchApi(this.ids).then(data => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.selWidth {
  width: 350px !important;
  height: 40px;
}

::v-deep .el-input--medium .el-input__inner {
  height: 40px;
  line-height: 40px;
}

.seachTiele {
  line-height: 40px;
}

.fa {
  color: #0a6aa1;
  display: block;
}

.sheng {
  color: #ff0000;
  display: block;
}
</style>
